import {create, query, remove, update} from "../services/menu";

export default {
    namespace: 'menu',

    state: {
        visible:false,
        currentItem:{},
        modalType: 'add',
    },
    subscriptions: {
        setup({dispatch}){
            dispatch({
                type:'query'
            })
        }
    },
    effects: {
        *query({payload},{call,put}){
            const data = yield call(query,payload)
            if(data.state === 0){
                yield put({
                    type:'querySuccess',
                    payload:{
                        list:data.data
                    }
                })
            }else{
                throw data
            }
        },
        *add({payload},{call,put}){
            const data = yield call(create,payload);
            if(data.message){
                yield put({type:'hideModal'})
                yield put({type:'/user/query'})
            }else{
                throw data
            }
        },
        *remove({payload},{call,put}){
            const data = yield call(remove,{...payload})
            if(data.message){
                yield put({type:'query'})
            }else{
                throw data
            }
        },
        *update({payload},{call,put}){
            const data = yield call(update,{...payload})
            if(data.message){
                yield put({type:'query'})
            }else{
                throw data
            }
        }
    },

    reducers: {
        querySuccess(state,{payload}){
            return {...state,...payload};
        },
        showModal(state,{payload}){
            return {...state,...payload,visible:true}
        },
        hideModal(state){
            return {...state,visible:false}
        }
    },
};
